package org.jflame.web.listener;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.jflame.commons.config.ConfigHolder;
import org.jflame.commons.util.StringHelper;

import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;

/**
 * servlet容器启动时加载properties配置文件.文件路径由ServletContext参数configFile指定
 * 
 * @author charles.zhang
 */
public class ConfigrationLoaderListener implements ServletContextListener {

    /**
     * 配置文件路径在ServletContext(web.xml)参数名
     */
    final String CONFIG_FILE_KEY = "configFile";

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        String configFile = sce.getServletContext()
                .getInitParameter(CONFIG_FILE_KEY);
        if (StringHelper.isNotEmpty(configFile)) {
            String[] propertiesFile = StringHelper.split(StringUtils.deleteWhitespace(configFile));
            try {
                ConfigHolder.loadProperties(propertiesFile);
            } catch (IOException e) {
                sce.getServletContext()
                        .log("load configFile error", e);
            }
        } else {
            sce.getServletContext()
                    .log("Not found servletContext parameter 'configFile'");
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }

}
